<template>
  <div>
    <el-table :data="configList" size="mini">
      <el-table-column label="key">
        <template slot-scope="{ row }">
          <el-input v-model="row.key" placeholder="请输入配置的key" clearable />
        </template>
      </el-table-column>
      <el-table-column label="value">
        <template slot-scope="{ row }">
          <el-input
            v-model="row.value"
            placeholder="请输入配置的value"
            clearable
          />
        </template>
      </el-table-column>
      <el-table-column width="80px">
        <template #header>
          <el-tooltip content="添加配置项" placement="top">
            <el-button
              icon="el-icon-plus"
              @click="configList.push({ key: '', value: '' })"
              size="small"
            ></el-button>
          </el-tooltip>
        </template>
        <template slot-scope="{ row, $index }">
          <el-popconfirm title="确定移除吗？" @confirm="deleteItem($index)">
            <el-tooltip slot="reference" content="移除" placement="left">
              <el-button icon="el-icon-close" size="small"></el-button>
            </el-tooltip>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
export default {
  name: 'configure',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  watch: {
    value: {
      immediate: true,
      handler (n, o) {
        if (o === undefined || o === null) {
          this.configList = []
        }
        if (n) {
          try {
            let val = JSON.parse(n)
            this.backfill(val)
          } catch (error) {
            this.$emit('input', '{}')
            console.error(error)
          }
        }
      }
    },
    configList: {
      deep: true,
      handler (n) {
        if (this.verifyKey(n)) {
          let retData = {}
          n.forEach(item => {
            if (item.key) {
              retData[item.key] = item.value
            }
          })
          this.$emit('input', JSON.stringify(retData))
        }
      }
    }
  },
  data () {
    return {
      configList: []
    }
  },
  methods: {
    backfill (val) {
      // 将传入的值回填，已存在的覆盖，不存在的push
      Object.keys(val).forEach(key => {
        let oldItemIndex = this.configList.findIndex(_item => _item.key == key)
        if (oldItemIndex != -1) {
          this.configList[oldItemIndex].value = val[key]
        } else {
          this.configList.push({
            key: key,
            value: val[key]
          })
        }
      })
    },
    deleteItem (index) {
      this.configList.splice(index, 1)
    },
    verifyKey (n) {
      if (n?.length > 0) {
        let keys = n.map(item => item.key).filter(item => !!item)
        for (let item of keys) {
          if (!/^[a-z]+$/i.test(item)) {
            this.toastMsg(`key只能输入小写字母`)
            return false
          }
        }
        // 判断key是否重复
        let isRepeat = keys.some(_ => keys.filter(__ => __ === _).length > 1)
        if (isRepeat) {
          this.toastMsg(`key不能相同`)
          return false
        }
      }
      return true
    },
    toastMsg (msg) {
      this.$swal.fire({
        titleText: msg,
        icon: 'warning',
        toast: true,
        timer: 3000,
        position: 'top',
        showConfirmButton: false
      })
    }
  }
}
</script>
